package cc.zy.base.hr.controller;

import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.DateUtil;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.ExamineSimple;
import cc.zy.base.hr.service.IExamineSimpleService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 考劵
 * ExamineSimple
 * @author TK
 * @time 2022/03/09 09:53:33
 */

@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class ExamineSimpleController extends BaseController {

    private static final Integer DEFAULT_TIME = 0;
    private static final Integer DEFAULT_TOTAL = 0;
    private static final Integer UNPUBLISHED = 14000;
    private static final Integer PUBLISHED = 14001;

    @Resource
    private final IExamineSimpleService examineSimpleService;


    @GetMapping(FebsConstant.VIEW_HR_PREFIX + "examineSimple")
    public String examineSimpleIndex() {
        return FebsUtil.hrView("examineSimple/examineSimple");
    }

    /**
     * @Description 跳转到添加试卷页
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "examineSimple/add")
    public String examineSimpleAdd() {
        return FebsUtil.hrView("examineSimple/examineSimpleAdd");
    }

    /**
     * @Description 跳转到添加试题页
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "examineSimple/questions/{id}")
    public String examineSimpleAddQuestions(@PathVariable Integer id, Model model) {
        resolveExamineSimpleModel(id, model, false);
        return FebsUtil.hrView("examineSimple/examineSimpleAddQuestions");
    }

    /**
     * @Description 跳转到修改试卷
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "examineSimple/update/{id}")
    public String examineSimpleUpdate(@PathVariable Integer id, Model model) {
        resolveExamineSimpleModel(id, model, false);
        return FebsUtil.hrView("examineSimple/examineSimpleUpdate");
    }

    /**
     * @Description 跳转到详情页
     * @return void
     * @Author TK
     * @Date 2022/3/11 18:43
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "examineSimple/detail/{id}")
    public String examineSimpleDetail(@PathVariable Integer id, Model model) {
        resolveExamineSimpleModel(id, model, true);
        return FebsUtil.hrView("examineSimple/examineSimpleDetail");
    }

    private void resolveExamineSimpleModel(Integer id, Model model, Boolean transform) {
        ExamineSimple examineSimple = examineSimpleService.findById(id);
        if (examineSimple.getCreateDate() != null) {
            model.addAttribute("createDateTime", DateUtil.getDateFormat(examineSimple.getCreateDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        if (examineSimple.getLastModifyDate() != null) {
            model.addAttribute("updateDateTime", DateUtil.getDateFormat(examineSimple.getLastModifyDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        model.addAttribute("examineSimple", examineSimple);
    }

    /**
     * @Description 加载所有数据
     * @param request:
     * @param examineSimple:
     * @return cc.zy.base.common.entity.FebsResponse
     * @Author TK
     */
    @GetMapping("examineSimple/list")
    @ResponseBody
    public FebsResponse examineSimpleList(QueryRequest request, ExamineSimple examineSimple) {

        log.debug("前台传来的对象是：" + examineSimple);

        Map<String, Object> dataTable = getDataTable(examineSimpleService.findExamineSimples(request, examineSimple));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * @Description 新增试卷
     * @param examineSimple: 新增试卷对象
     * @return cc.zy.base.common.entity.FebsResponse
     * @Author TK
     * @Date 2022/3/7 15:47
     */
    @PostMapping("examineSimple/add")
    @ResponseBody
    @ControllerEndpoint(operation = "新增试卷", exceptionMessage = "新增试卷异常")
    public FebsResponse addExamineSimple(@Valid ExamineSimple examineSimple) {

        log.debug("前台传来的对象是：" + examineSimple);

        //判断前台是否输入了考试时间，如果没输入，给个默认值
        if (examineSimple.getMinutes() == null || "".equals(examineSimple.getMinutes())) {
            examineSimple.setMinutes(DEFAULT_TIME);
        }
        //设置考题初始创建分数为
        examineSimple.setTotal(DEFAULT_TOTAL);
        //设置考卷的初始状态为未发布
        examineSimple.setPublish(UNPUBLISHED);
        //创建随机生成的六位数考试登录密码
        examineSimple.setRandPwd((int)((Math.random()*9+1)*100000));
        examineSimple.setCreateStaffId(FebsUtil.getCurrentUser().getUserId());
        examineSimple.setLastModifyStaffId(FebsUtil.getCurrentUser().getUserId());

        examineSimpleService.createExamineSimple(examineSimple);

        return new FebsResponse().success();
    }

    /**
     * @Description 试卷删除
     * @param examineSimpleIds: 删除对象
     * @return cc.zy.base.common.entity.FebsResponse
     * @Author TK
     */
    @GetMapping("examineSimple/delete/{examineSimpleIds}")
    @ControllerEndpoint(operation = "删除试卷", exceptionMessage = "删除试卷异常")
    @ResponseBody
    public FebsResponse deleteExamineSimples(@NotBlank(message = "{required}") @PathVariable String examineSimpleIds) {

        log.debug("前台传来的对象是：" + examineSimpleIds);

        String[] ids = examineSimpleIds.split(StringPool.COMMA);

        examineSimpleService.deleteExamineSimples(ids);

        return new FebsResponse().success();
    }

    /**
     * @Description 试卷上传
     * @param id: 删除对象
     * @return cc.zy.base.common.entity.FebsResponse
     * @Author TK
     */
    @GetMapping("examineSimple/publish/{id}")
    @ControllerEndpoint(operation = "上传试卷", exceptionMessage = "上传试卷异常")
    @ResponseBody
    public FebsResponse publishExamineSimples(@NotBlank(message = "{required}") @PathVariable String id) {

        log.debug("前台传来的对象是：" + id);

        if (id == null || "".equals(id)) {
            throw new FebsException("试卷ID为空");
        }
        ExamineSimple examineSimple = examineSimpleService.findById(Integer.valueOf(id));
        if (examineSimple.getMinutes() == 0 ){
            throw new FebsException("考试时长不能为0");
        }
        if (examineSimple.getTotal() == 0 ){
            throw new FebsException("试卷总分不能为0");
        }
        examineSimple.setPublish(PUBLISHED);
        examineSimpleService.updateExamineSimple(examineSimple);

        return new FebsResponse().success();
    }

    /**
     * @Description 试卷修改
     * @param examineSimple:
     * @return cc.zy.base.common.entity.FebsResponse
     * @Author TK
     */
    @PostMapping("examineSimple/update")
    @ControllerEndpoint(operation = "修改试卷", exceptionMessage = "修改试卷信息异常")
    @ResponseBody
    public FebsResponse updateExamineSimple(@Valid ExamineSimple examineSimple) {

        log.debug("修改试卷id：" + examineSimple.getId());

        if (examineSimple.getId() == null) {
            throw new FebsException("试卷ID为空");
        }

        examineSimple.setLastModifyStaffId(FebsUtil.getCurrentUser().getUserId());
        examineSimple.setLastModifyDate(new Date());

        examineSimpleService.updateExamineSimple(examineSimple);

        return new FebsResponse().success();
    }

    /**
     * @Description excel导出
     * @param response:
     * @param examineSimple:
     * @return void
     * @Author TK
     */
    @GetMapping("examineSimple/excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, ExamineSimple examineSimple) {

        log.debug(String.format("response = %s", response));
        log.debug(String.format("ExamineSimple = %s", examineSimple));

        List<ExamineSimple> examineSimples = examineSimpleService.findExamineSimpleListNotPage(examineSimple);
        ExcelKit.$Export(ExamineSimple.class, response).downXlsx(examineSimples, false);
    }

    /**
     * 方法描述：查找试卷
     *
     * @param examineSimpleId 试卷id
     * @return cc.zy.base.common.entity.FebsResponse
     */
    @GetMapping("examineSimple/findById/{examineSimpleId}")
    @ResponseBody
    public FebsResponse findById(@PathVariable Integer examineSimpleId) {

        log.debug(String.format("examineSimpleId = %s", examineSimpleId));

        ExamineSimple examineSimple = examineSimpleService.findById(examineSimpleId);
        return new FebsResponse().success().data(examineSimple);
    }


    /**
     * 增加功能中，查询前台输入的试卷名是否存userAdd.html在
     *
     * @param title
     * @return Boolean false为重复
     * true为不重复
     */
    @GetMapping("examineSimple/isRepetitive")
    @ResponseBody
    public Boolean isRepetitive(String title) {

        log.debug("前台输入试卷名称：" + title);

        return examineSimpleService.isRepetitive(title);
    }
}
